/* eslint-disable no-param-reassign */
import { AddressList, DeleteAddress } from '../../../../services/address/address';
import util from "../../../../utils/util.js";
import { resolveAddress, rejectAddress } from './util';

Page({
  data: {
    addressList: [],
    deleteID: '',
    showDeleteConfirm: false,
  },

  /** 选择模式 */
  selectMode: false,
  /** 是否已经选择地址，不置为true的话页面离开时会触发取消选择行为 */
  hasSelect: false,

  onLoad(query) {
    const { selectMode = '', id = '' } = query;
    this.setData({
      id,
    });
    this.selectMode = !!selectMode;
    this.init();
  },
  init() {
    this.getAddressList();
  },
  onShow() {
    if (this.data.refresh) this.init();   // 新增编辑完刷新
  },
  onUnload() {
    if (this.selectMode && !this.hasSelect) {
      rejectAddress();
    }
  },
  getAddressList() {
    AddressList({}).then(res => {
      if (res.code === '0000') {
        this.setData({ addressList: res.data });
      }
    });
  },
  /* 删除 */
  deleteAddressHandle(e) {
    const { id } = e.currentTarget.dataset;
    let that = this;
    wx.showModal({
      title: "",
      content: "是否确认删除该地址？",
      showCancel: true,
      success: function (cif) {
        if (cif.confirm) {
          DeleteAddress({ memberAddressId: id }).then(res => {
            if (res.code === '0000') {
              util.showToast("删除成功")
              that.getAddressList()
            }
          })
        }
      }
    });
  },
  /* 新增 */
  createHandle() {
    wx.navigateTo({ url: '/pages/usercenter/address/edit/index' });
  },
  /* 编辑 */
  editAddressHandle({ detail }) {
    let locationState = JSON.stringify(detail)
    wx.navigateTo({ url: `/pages/usercenter/address/edit/index?locationState=${locationState}` });
  },
  selectHandle({ detail }) {
    if (this.selectMode) {
      this.hasSelect = true;
      resolveAddress(detail);
      wx.navigateBack({ delta: 1 });
    } else {
      this.editAddressHandle({ detail });
    }
  },

});
